const fs = require('fs').promises;
const path = require('path');

// 读取JSON文件
const readJsonFile = async (filename) => {
  try {
    const filePath = path.join(__dirname, '../data', filename);
    console.log('Reading file:', filePath);
    const data = await fs.readFile(filePath, 'utf8');
    console.log('File content:', data);

    // 确保数据是有效的JSON
    let parsed;
    try {
      parsed = JSON.parse(data);
    } catch (parseError) {
      console.error('JSON parse error:', parseError);
      return [];
    }

    // 确保数据是数组
    if (!Array.isArray(parsed)) {
      console.error('Data is not an array:', parsed);
      return [];
    }

    console.log('Parsed data:', parsed);
    return parsed;
  } catch (error) {
    console.error('Error reading file:', error);
    if (error.code === 'ENOENT') {
      // 如果文件不存在，返回空数组
      return [];
    }
    throw error;
  }
};

// 写入JSON文件
const writeJsonFile = async (filename, data) => {
  try {
    const filePath = path.join(__dirname, '../data', filename);
    await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8');
    console.log('Successfully wrote to file:', filePath);
  } catch (error) {
    console.error('Error writing to file:', error);
    throw error;
  }
};

module.exports = {
  readJsonFile,
  writeJsonFile
}; 